<?php

namespace plugins\assets\controller;

use app\controller\backend\BaseController;
use app\model\Website;
use plugins\assets\model\AssetsDomain;
use plugins\assets\validate\AssetsDomainValidate;
use think\exception\ValidateException;

class DomainController extends BaseController
{
    public function index()
    {
        $param = $this->request->only([
            'limit' => 10,
        ]);

        $where = [];

        //获取当前站点里的域名，添加进域名列表
        $websiteModel = new Website();
        $domainModel = new AssetsDomain();

        $siteListRes = $websiteModel->getAllCustomData([], 'id asc', 'id, domain, title');
        $siteList = $siteListRes['data'];
        $domainList = [];
        $insertData = [];
        foreach ($siteList as $value) {
            $domainList[$value['domain']] = $value;
            if ($domainModel->isExist(['domain' => $value['domain']])) {
                continue;
            }
            $insertData[] = [
                'domain' => $value['domain'],
                'desc' => $value['title'],
                'sort' => 1000
            ];
        }
        $domainModel->insertAll($insertData);

        $list = $domainModel->getList($where, ['admin'], $param['limit'], 'id asc, sort desc', '*');

        $res = pageReturn($list);
        foreach ($res['data'] as &$v) {
            if (isset($domainList[$v['domain']])) {
                $v['domain'] .= '(本系统域名)';
            }
        }

        return json($res);
    }

    public function add()
    {
        $param = $this->request->post([
            'domain' => '',
            'desc' => '',
            'holder_name' => '',
            'registrants' => '',
            'price' => '',
            'status' => '',
            'register_date' => '',
            'expire_date' => '',
        ]);

        try {
            validate(AssetsDomainValidate::class)->scene('save')->check($param);
        } catch (ValidateException $e) {
            return jsonReturn(-1, $e->getError());
        }

        $domainModel = new AssetsDomain();
        if ($domainModel->isExist(['domain' => $param['domain']])) {
            return jsonReturn(-2, lang('域名已经存在'));
        }

        if (empty($param['register_date'])) unset($param['register_date']);

        if (empty($param['expire_date'])){
            unset($param['expire_date']);
        } else {
            $day = (strtotime($param['expire_date']) - time()) / (60*60*24);
            if ($day > 0) {
                $param['hint'] = lang('还有').$day.lang("天过期");
            } else {
                $day = abs($day);
                $param['hint'] = lang('域名已过期').$day.lang("天");
            }
        }
        $param['seller_id'] = $this->admin['seller_id'];

        $res = $domainModel->add($param);

        return json($res);
    }

    public function edit()
    {
        $param = $this->request->post([
            'id' => 0,
            'domain' => '',
            'desc' => '',
            'holder_name' => '',
            'registrants' => '',
            'price' => '',
            'status' => '',
            'register_date' => '',
            'expire_date' => '',
        ]);
        try {
            validate(AssetsDomainValidate::class)->scene('update')->check($param);
        } catch (ValidateException $e) {
            return jsonReturn(-1, $e->getError());
        }
        $domainModel = new AssetsDomain();
        if ($domainModel->isExist([
            ['id', '<>', $param['id']],
            ['domain', '=', $param['domain']]
        ])) {
            return jsonReturn(-2, lang('域名已经存在'));
        }

        if (empty($param['register_date'])) unset($param['register_date']);
        if (empty($param['expire_date'])){
            unset($param['expire_date']);
        } else {
            $day = (strtotime($param['expire_date']) - time()) / (60*60*24);
            if ($day > 0) {
                $param['hint'] = lang('还有').$day.lang("天过期");
            } else {
                $day = abs($day);
                $param['hint'] = lang('域名已过期').$day.lang("天");
            }
        }

        $res = $domainModel->edit(['id' => $param['id']], $param);

        return json($res);
    }

    public function del()
    {
        $param = $this->request->post([
            'id' => 0,
        ]);
        try {
            validate(AssetsDomainValidate::class)->scene('del')->check($param);
        } catch (ValidateException $e) {
            return jsonReturn(-1, $e->getError());
        }

        $domainModel = new AssetsDomain();
        $res = $domainModel->where(['id' => $param['id']])->delete();
        if ($res === false) {
            return jsonReturn(-1, lang('删除失败'));
        }
        return jsonReturn(0, lang('删除成功'));
    }

    public function whois()
    {
        $param = $this->request->post([
            'id' => 0,
        ]);

        $domainModel = new AssetsDomain();
        $domain = $domainModel->where('id', $param['id'])->value('domain');
        if (empty($domain)) {
            return jsonReturn(-1, lang('没找到域名数据'));
        }

        $this->execWhois($domain);

        return jsonReturn(0, lang('执行成功！'));
    }

    public function execWhois($domain)
    {
        $domainModel = new AssetsDomain();
        $id = $domainModel->where('domain', $domain)->value('id');
        $domain = url_root($domain);

        // 执行命令
        $res = `whois {$domain}`;

        $domainModel->where('id', $id)->update(['whois' => $res]);

        $infoArr = explode("\n", $res);
        $newInfo = [];
        foreach ($infoArr as $value) {
            $info = explode(': ', $value);
            if (!isset($info[1])) continue;
            $newInfo[$info[0]] = trim($info[1]);
        }

        if (count($newInfo) < 5) {
            // 没查到
            return jsonReturn(-1, lang('执行失败！whois查询失败'));
        }

        $expire_date = null;
        if (isset($newInfo['Registry Expiry Date'])) {
            $expire_date = date('Y-m-d H:i:s', strtotime($newInfo['Registry Expiry Date']));
        }
        if (isset($newInfo['Registrar Registration Expiration Date'])) {
            $expire_date = date('Y-m-d H:i:s', strtotime($newInfo['Registrar Registration Expiration Date']));
        }

        $hint = '';
        if (!empty($expire_date)) {
            $day = (strtotime($expire_date) - time()) / (60*60*24);
            $day = intval($day);
            if ($day > 0) {
                $hint =  lang('还有').$day.lang("天过期");
            } else {
                $day = abs($day);
                $hint = lang('域名已过期').$day.lang("天");
            }
        }

        $updateData = [
            'status' => $newInfo['Domain Status'] ?? '',
            'register_date' => isset($newInfo['Creation Date']) ? date('Y-m-d H:i:s', strtotime($newInfo['Creation Date'])) : null,
            'expire_date' => $expire_date,
            'holder_name' => $newInfo['Registrant Organization'] ?? '',
            'registrants' => $newInfo['Registrar'] ?? '',
            'hint' => $hint,
        ];

        $domainModel->where('id', $id)->update($updateData);
    }
}